package conf

import (
	"fmt"
	"github.com/go-ini/ini"
	"log"
)

// https://zhuanlan.zhihu.com/p/652564560?utm_id=0
var (
	Cig           *ini.File
	DbAlias       string
	DbName        string
	DbUser        string
	DbPwd         string
	DbHost        string
	DbPort        string
	DbCharset     string
	TbPrefix      string
	RedisHost     string
	RedisPort     string
	RedisPassword string
)

type Database struct {
	DbAlias   string
	DbName    string
	DbUser    string
	DbPwd     string
	DbHost    string
	DbPort    string
	DbCharset string
	TbPrefix  string
}

type Redis struct {
	RedisHost      string
	RedisPort      string
	RedisPassword1 string
	RedisPassword2 string
}

type RedisCluster struct {
	RedisClusterHost     string
	RedisClusterPort     string
	RedisClusterPassword string
}

var DatabaseSetting = &Database{}
var RedisSetting = &Redis{}
var RedisClusterSetting = &RedisCluster{}

func Load() {
	fmt.Println("init database.....")
	appConfig, err := ini.Load("conf/app.ini")
	if err != nil {
		log.Fatalf("加载初始化文件 'conf/app.ini' 文件失败: %v", err)
	}
	err = appConfig.Section("database").MapTo(DatabaseSetting)
	if err != nil {
		log.Fatalf("config mapTo DatabaseSetting err: %v", err)
	}
	err = appConfig.Section("redis").MapTo(RedisSetting)
	if err != nil {
		log.Fatalf("config mapTo redis err: %v", err)
	}
	err = appConfig.Section("redisCluster").MapTo(RedisClusterSetting)
	if err != nil {
		log.Fatalf("config mapTo redis err: %v", err)
	}
	/*	sec, err := appConfig.GetSection("database")
		if err != nil {
			log.Fatalf("Fail to get section 'databse': %v", err)
		}
		DbAlias = sec.Key("db_alias").MustString("")
		DbName = sec.Key("db_name").MustString("")
		DbUser = sec.Key("db_user").MustString("")
		DbPwd = sec.Key("db_pwd").MustString("")
		DbHost = sec.Key("db_host").MustString("")
		DbPort = sec.Key("db_port").MustString("")
		DbCharset = sec.Key("db_charset").MustString("")
		TbPrefix = sec.Key("tb_prefix").MustString("")

		secRedis, err := appConfig.GetSection("redis")
		if err != nil {
			log.Fatalf("Fail to get section 'redis': %v", err)
		}
		RedisHost = secRedis.Key("redis_host").MustString("")
		RedisPort = secRedis.Key("redis_port").MustString("")
		RedisPassword = secRedis.Key("redis_password").MustString("")*/
	ConnectDataBaseAndRegisterDataBaseModel()
	ConnectRedis()
}
